package com.partsoft.dits.log;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.spi.OptionHandler;
import org.springframework.util.ClassUtils;

public class DbcpLayout extends BaseDataSourceLogAdapter implements LogAdapter, OptionHandler {
	
	private String driverClassName;
	
	private String validationQuery;
	
	private String url;
	
	private String username;
	
	private String password;
	
	private int initialSize = 1;
	
	private int maxActive = 5;
	
	private int maxWait = -1;
	
	private boolean testOnBorrow = true;
	
	public DbcpLayout() {
		super();
	}
	
	@Override
	public void activateOptions() {
		try {
			ClassUtils.forName(getDriverClassName(), Thread.currentThread().getContextClassLoader());
		} catch (Exception e) {
			throw new IllegalArgumentException(String.format("日志的DBCP连接池设置错误：JDBC驱动类(%s)找不到。", getDriverClassName()), e);
		}
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(getDriverClassName());
		ds.setValidationQuery(getValidationQuery());
		ds.setUrl(getUrl());
		ds.setUsername(getUsername());
		ds.setPassword(getPassword());
		ds.setDefaultAutoCommit(false);
		ds.setInitialSize(getInitialSize());
		ds.setMaxActive(5);
		ds.setMaxWait(getMaxWait());
		ds.setTestOnBorrow(isTestOnBorrow());
		setDataSource(ds);
		super.activateOptions();
	}

	public String getDriverClassName() {
		return driverClassName;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public String getValidationQuery() {
		return validationQuery;
	}

	public void setValidationQuery(String validationQuery) {
		this.validationQuery = validationQuery;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getInitialSize() {
		return initialSize;
	}

	public void setInitialSize(int initialSize) {
		this.initialSize = initialSize;
	}

	public int getMaxActive() {
		return maxActive;
	}

	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}

	public int getMaxWait() {
		return maxWait;
	}

	public void setMaxWait(int maxWait) {
		this.maxWait = maxWait;
	}

	public boolean isTestOnBorrow() {
		return testOnBorrow;
	}

	public void setTestOnBorrow(boolean testOnBorrow) {
		this.testOnBorrow = testOnBorrow;
	}
	
}
